package com.tapstitch.scm.common.utils;

import com.bluebuck.quickboot.core.enums.Language;
import com.tapstitch.scm.common.constant.Constants;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class RequestInfoUtil {

	private static final Language LANGUAGE_DEFAULT = Language.US_ENGLISH;

	public static Language getCurrentRequestLanguage(){
		return getCurrentRequestLanguage(getCurrentRequest());
	}

	public static Language getCurrentRequestLanguage(HttpServletRequest currentRequest){
		if(currentRequest == null) {
			return LANGUAGE_DEFAULT;
		}
		String language = currentRequest.getHeader(Constants.LANGUAGE_HEADER_KEY);
		return Language.getInstance(language, LANGUAGE_DEFAULT);
	}

	public static boolean isAjaxRequest() {
		HttpServletRequest request = getCurrentRequest();
		if (request == null) {
			return false;
		}
		String xRequestedWith = request.getHeader("X-Requested-With");
		if (xRequestedWith == null || xRequestedWith.trim().length() == 0) {
			return false;
		}
		return true;
	}

	public static HttpServletRequest getCurrentRequest() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		if (!(requestAttributes instanceof ServletRequestAttributes)) {
			return null;
		}
		return ((ServletRequestAttributes) requestAttributes).getRequest();
	}

	/**
	 * 获取客户端ip
	 *
	 * @return
	 */
	public static String getRemoteHost() {
		return getRemoteHost(getCurrentRequest());
	}

	/**
	 * 获取客户端ip
	 *
	 * @param request
	 * @return
	 */
	public static String getRemoteHost(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && ip.split(",").length > 1) {
			ip = ip.split(",")[0];
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	public static String getReferer(HttpServletRequest request) {
		String referer = request.getHeader("referer");
		if(referer == null) {
			referer = request.getHeader("Referer");
		}
		return referer;
	}
}
